<?php
/**
 * Created by PhpStorm.
 * User: houyuesong
 * Date: 2020/4/8
 * Time: 18:26
 * Desc: 权限基类
 */
declare (strict_types=1);

namespace app\api\base\controller;

use app\BaseController;
use app\extend\model\User;
use think\facade\Cache;
use think\facade\Lang;

class Base extends BaseController
{
    protected static $UserInfo = [];

    public function initialize()
    {
        header('Access-Control-Allow-Origin: *');

        header('Access-Control-Allow-Methods: *');

        header('Access-Control-Allow-Headers: *');

        $this->_auth();
    }

    /**
     * 权限
     */
    private function _auth(): void
    {
        // 获取 URL 参数中的 lang 参数，默认为 'zh-cn'
        $language = input('language','zh');

        // 设置语言包
        Lang::setLangSet($language);

        $controller = request()->controller();
        $action = request()->action();

        //过滤权限效验
        if (in_array($controller . '/' . $action, [
            'Login/index',
            'Register/index',
            'Home/getHotProductAll',
            'Home/getBannerAll',
            'News/getAll',
            'News/getDetail',
            'Websiteconfig/getDetail'
        ])) {
            return;
        }

        //获取token
        $token = input('X-Token','');

        $userId = Cache::get($token);

        if (empty($userId)) {
            exit(json_encode(_E('Token过期', [], 500002)));
        }

        $userInfo = User::where([
            ['id', '=', $userId]
        ])->append(['level_name_txt'])->field('id,account,mobile,level_id,balance,rixibao_money,is_delete')->find();

        if (empty($userInfo)) {
            exit(json_encode(_E('用户不存在', [], 500003)));
        }

        if ($userInfo->is_delete == 1) {
            exit(json_encode(_E('用户状态禁用', [], 500004)));
        }

        $userInfo->token = $token;
        self::$UserInfo = $userInfo;
    }
}
